package com.ht.api.task.ad;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.Plan;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.open.OpenUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;

/**
 * 检查朋友圈发布状态
 */
@Slf4j
public class CheckMomentStatusTask implements TaskHandler {

    /** 接口ID：获取朋友圈任务创建结果 */
    protected static final long API_ID = 1900850595795963904L;

	@Override
	public String getName() {
		return "检查朋友圈发布状态";
	}

    @Override
    public boolean handler(JSONObject requestParam, String groupId, long taskId) {
        long tenantId = requestParam.getLong("tenant_id");
        DataSource ds = DbConfig.useTenantDb(tenantId);

        String adTaskGroupId = requestParam.getStr("ad_task_group_id");

        String jobid = requestParam.getStr("jobid");
        String appid = requestParam.getStr("appid");

        JSONObject param = JSONUtil.createObj();
        param.set("jobid", jobid);

        String str = OpenUtil.call(appid, API_ID, param);

        JSONObject result = JSONUtil.parseObj(str);

        int status = result.getInt("status");
        if (status == 3) {
            String momentId = result.getByPath("result.moment_id", String.class);

            Entity adTaskGroup = Entity.create("ad_task_group");
            adTaskGroup.setMainId(adTaskGroupId);
            adTaskGroup.set("business_id", momentId);
            adTaskGroup.set("status", 3);

            Db.insert(ds, adTaskGroup);

            JSONObject checkMomentUserStatusParam = JSONUtil.createObj();
            checkMomentUserStatusParam.set("appid", appid);
            checkMomentUserStatusParam.set("moment_id", momentId);
            checkMomentUserStatusParam.set("tenant_id", tenantId);
            checkMomentUserStatusParam.set("ad_task_group_id", adTaskGroupId);
            HtTaskExecutor.submitTask(checkMomentUserStatusParam, new CheckMomentUserStatusTask(),
                    Plan.create().setMin(10).setRate(2).setMax(60).setTimes(2, TimeUnit.DAYS));


            log.info("朋友圈平台创建成功 success......");
            HtTaskExecutor.stopTask(taskId);
        } else {
            log.info("检查朋友圈状态中 success......");
        }


        return true;
    }
}
